import axios from "axios";
import { rootPath } from "@/config/globalParam";
import { Message } from "element-ui";

/**
 * 导出excel文件
 * fileName 文件的名称 请自带xlsx文件后缀
 * url 请求全路径
 * param 参数
 */
export default async (fileName, param = {}, url) => {
  let readyMes = Message.success({
    message: "开始下载，请耐心等待...",
    duration: 3000,
    showClose: false
  });
  return axios
    .post(url, param, {
      responseType: "blob",
      baseURL: rootPath,
      timeout: 1800000,
      withCredentials: true, // 是否允许带cookie这些
      headers: {
        "content-Type": "application/json",
        Authorization: "Bearer "
      }
    })
    .then(res => {
      //返回结果为空
      if (!res) {
        Message.error("发生错误！请重新操作");
        return;
      }
      //返回结果不是200，抛出错误提示
      if (res.status != "200") {
        Message.error("请求发生错误，请联系管理员");
        return;
      }
      let file = res.data;
      let fileReader = new FileReader();
      fileReader.onload = function() {
        try {
          let jsonData = JSON.parse(this.result);
          if (jsonData.status == "0") {
            // 说明是普通对象数据，后台转换失败
            // to do something
            readyMes.close();
            status0(jsonData.msg);
          }
        } catch (err) {
          // 解析成对象失败，说明是正常的文件流
          downBlob(file, fileName);
        }
      };
      fileReader.readAsText(file);
    });
};

function status0(msg) {
  if (msg.length > 15 && msg.length < 20) {
    Message.error({
      message: msg,
      duration: 6000
    });
  } else if (msg.length >= 20) {
    Message.error({
      message: msg,
      duration: 0,
      showClose: true
    });
  } else {
    msg ? Message.error(msg) : Message.error("服务器发生错误[NO Message]");
  }
}

function downBlob(content, fileName) {
  const blob = new Blob([content]);
  if (
    "download" in document.createElement("a") &&
    typeof window.navigator.msSaveBlob === "undefined"
  ) {
    // 非IE下载
    const elink = document.createElement("a");
    elink.download = fileName;
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // 释放URL 对象
    document.body.removeChild(elink);
  } else {
    // IE10+下载 IE & Edge
    navigator.msSaveBlob(blob, fileName);
  }
}
